<template>
  <div v-if="currentReq" class="container w-75 m-auto mt-5">
    <div class="row gutters-sm">
      <div class="card p-0">
        <div class="card-header text-muted text-center">
          изменено {{ status_str(currentReq.current_status.datetime) }}
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-sm-3">
              <h6 class="mb-0">Тема</h6>
            </div>
            <div class="col-sm-9" v-html="currentReq.topic"></div>
          </div>
          <hr />
          <div class="row">
            <div class="col-sm-3">
              <h6 class="mb-0">Состояние</h6>
            </div>
            <div class="col-sm-4 d-flex">
              <select v-if="is_changing" class="form-control" v-model="status" aria-label="Default select example">
                <option v-if="currentReq.current_status.status != 'closed'" :value="'closed'">Закрыто</option>
                <option v-if="currentReq.current_status.status != 'in_progress' && user.role != 'user'"
                  :value="'in_progress'">
                  В работе
                </option>
                <option v-if="currentReq.current_status.status != 'open' && user.role != 'user'" :value="'open'">Открыто
                </option>
              </select>
              <div class="me-3" v-else>
                {{ ru_status(currentReq.current_status.status) }}
              </div>
              <div v-if="user.role == 'user' && currentReq.current_status.status != 'closed' || user.role != 'user'">
                <button v-if="!is_changing" @click="is_changing = true" class="btn btn-primary mb-3">
                  Изменить
                </button>
                <button v-else @click="save">Сохранить</button>
              </div>

            </div>
          </div>
          <hr v-if="user.role != 'user'" />
          <div v-if="user.role != 'user'" class="row">
            <div class="col-sm-3">
              <h6 class="mb-0">Пользователь</h6>
            </div>
            <div class="col-sm-9">
              <router-link :to="'/user/' + currentReq.user.id">{{
                currentReq.user.name
              }}</router-link>
            </div>
          </div>
          <hr v-if="user.role != 'user'" />
          <div v-if="user.role != 'user'" class="row">
            <div class="col-sm-3">
              <h6 class="mb-0">Организация</h6>
            </div>
            <div class="col-sm-9">
              <router-link :to="'/organization/' + currentReq.user.organization.id">{{
                currentReq.user.organization.name
              }}</router-link>
            </div>
          </div>
          <hr v-if="user.role != 'user'" />
          <div v-if="user.role != 'user'" class="row">
            <div class="col-sm-3">
              <h6 class="mb-0">ИНН</h6>
            </div>
            <div class="col-sm-9">{{
              currentReq.user.organization.inn
            }}
            </div>
          </div>
          <hr />
          <div class="row">
            <div class="col-sm-3">
              <h6 class="mb-0">Подробности</h6>
            </div>
            <div class="col-sm-9" v-html="md_description"></div>
          </div>
          <hr v-if="user.role != 'user' && !is_replying && currentReq.current_status.status == 'open'
            " />
          <div v-if="user.role != 'user' && !is_replying && currentReq.current_status.status == 'open'
            " class="row">
            <div class="col-sm-12">
              <button type="button" @click="is_replying = true" class="btn btn-info">
                Ответить
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="container w-75 m-auto mt-3" v-if="currentResp">
    <div class="main-body">
      <div class="row gutters-sm">
        <div class="card mb-3">
          <div class="card-body">
            <div class="row">
              <div class="col-sm-3">
                <h6 class="mb-0">Ответ</h6>
              </div>
              <div class="col-sm-9" v-html="md_response"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div v-if="!is_continue && user.role == 'user' && currentReq && currentReq.current_status.status == 'in_progress'"
    class="container w-75">
    <button @click="is_continue = true" class="form-control btn btn-info">
      Продолжить тему
    </button>
  </div>
  <div v-if="is_continue" class="container w-75">
    <form v-if="tokens">
      <div class="mb-3">
        <label for="field1" class="form-label">Тема</label>
        <input type="text" :class="'form-control ' + get_msg_class('topic')" id="field1" aria-describedby="emailHelp"
          v-model="topic" />
        <div class="invalid-feedback">
          {{ get_msg("topic") }}
        </div>
      </div>
      <div class="mb-3">
        <label for="field2" class="form-label">Подробности</label>
        <vue-easymde id="field2" v-model="description" :options="{
          lineNumbers: true,
          renderingConfig: {
            codeSyntaxHighlighting: true,
          },
          showIcons: ['code', 'undo', 'redo'],
          spellChecker: false,
          styleSelectedText: false,
        }" />
      </div>
      <button type="button" class="btn btn-primary" @click="createReq(tokens.access_token)">
        Отправить
      </button>
    </form>
    <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
  </div>

  <div class="container w-75 m-auto mt-3" v-if="is_replying">
    <form v-if="tokens">
      <div class="mb-3">
        <label for="field2" class="form-label">Ответ</label>
        <vue-easymde id="field2" v-model="description" :options="{
          lineNumbers: true,
          renderingConfig: {
            codeSyntaxHighlighting: true,
          },
          showIcons: ['code', 'undo', 'redo'],
          spellChecker: false,
          styleSelectedText: false,
        }" />
      </div>
      <button type="button" class="btn btn-primary" @click="sendForm(tokens.access_token)">
        Отправить
      </button>
      <h3 :class="msg_class">{{ msg }}</h3>
    </form>
  </div>
  <h3 class="text-danger">{{ error }}</h3>
</template>

<script>
import VueBasicAlert from "vue-basic-alert";
import { useFetch } from "@vueuse/core";
import { marked } from "marked";

export default {
  props: {
    id: Number,
    tokens: Object,
    user: Object,
  },
  components: {
    VueBasicAlert
  },
  data() {
    return {
      is_continue: false,
      topic: "",
      description: "",
      is_changing: false,
      error: "",
      currentReq: undefined,
      status: undefined,
      currentResp: undefined,
      is_replying: false,
      description: "",
      msg: "",
      msg_class: "",
      detail: [],
    };
  },
  mounted() {
    this.getReq(this.tokens.access_token);
  },
  computed: {
    md_description() {
      if (this.currentReq != undefined) {
        return marked.parse(this.currentReq.description);
      } else {
        return "";
      }
    },
    md_response() {
      if (
        this.currentResp != undefined &&
        this.currentResp.description != undefined
      ) {
        return marked.parse(this.currentResp.description);
      } else {
        return "";
      }
    },
  },
  methods: {
    get_msg_class(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = "is-invalid";
        }
      });
      return ans;
    },
    get_msg(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = el.msg;
        }
      });
      return ans;
    },
    createReq(token) {
      this.detail = [];
      this.topic = `<a href="/req/${this.currentReq.id}">Прошлый</a> ${this.topic}`;
      fetch(`${process.env.VUE_APP_BASE_URI}/req/create`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          topic: this.topic,
          description: this.description,
        }),
      }).then(
        (resp) => {
          if (resp.status != 500) {
            resp.json().then(
              (body) => {
                if (resp.ok) {
                  this.detail = [];
                  this.topic = "";
                  this.description = "";
                  this.status = 'closed';
                  this.save();
                  this.is_continue = false;
                  this.$refs.alert.showAlert(
                    "success",
                    "Вы успешно отпарвили заявление. Ждите обработки",
                    "Отравлено"
                  );
                  this.$router.push(`/req/${body.id}`)
                } else {
                  this.$refs.alert.showAlert(
                    "error",
                    `${resp.statusText}`,
                    "Ошибка"
                  );
                }
                if (resp.status == 422) {
                  this.detail = body.detail;
                }
              },
              () => {
                this.$refs.alert.showAlert(
                  "error",
                  "Ошибка сервера",
                  "Ошибка обработки json"
                );
              }
            );
          } else {
            this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
          }
        },
        (err) => {
          this.$refs.alert.showAlert("error", "Ошибка сервера", err.message);
        }
      );
    },
    ru_status(status) {
      if (status == "open") {
        return "открыта"
      } else if (status == "in_progress") {
        return "в разработке"
      } else {
        return "закрыта"
      }
    },
    status_str(dateStr) {
      const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
      let date = new Date(Date.parse(dateStr))
      let count = this.day_count(dateStr);
      if (count == 0) {
        return `сегодня в ${date.toLocaleTimeString()}`
      } else if (count == 1) {
        return `вчера в ${date.toLocaleDateString()}`
      } else {
        return date.toLocaleDateString(undefined, options)
      }
    },
    day_count(dateStr) {
      const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
      const now = new Date().getTime();
      const date = Date.parse(dateStr);

      return Math.floor(Math.abs((date - now) / oneDay));
    },
    save() {
      let token = this.tokens.access_token;
      const { data, onFetchError, onFetchResponse } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/req/${this.id}/${this.status}`,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      ).put();

      onFetchError((error) => {
        this.error += error.message;
      });

      onFetchResponse(() => {
        this.currentReq.current_status = JSON.parse(data.value);
      });
      this.is_changing = false;
    },
    getReq(token) {
      const { isFetching, data, onFetchError, onFetchResponse } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/req/${this.id}`,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      ).get();

      onFetchError((error) => {
        this.error += error.message;
      });

      onFetchResponse(() => {
        this.currentReq = JSON.parse(data.value);
        console.log(this.currentReq.current_status.status)
        if (this.currentReq.current_status.status != "open") {
          this.getResp(this.id, this.tokens.access_token);
        }
      });
      return { isFetching };
    },
    getResp(req_id, token) {
      const { isFetching, data, onFetchError, onFetchResponse } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/resp/${req_id}`,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      ).get();
      onFetchError((error) => {
        this.error += error.message;
      });

      onFetchResponse(() => {
        this.currentResp = JSON.parse(data.value);
      });
      return { isFetching };
    },
    sendForm(token) {
      let id = this.id;
      const { isFetching, data, onFetchResponse, onFetchError } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/resp/${id}/`,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      ).post({
        description: this.description,
      });

      onFetchResponse(() => {
        location.reload();
      });

      onFetchError((error) => {
        this.msg = error.message;
        this.msg_class = "text-danger";
      });
      return {
        isFetching,
        data,
      };
    },
  },
};
</script>

<style></style>